package com.jzo2o.health.config;

import com.jzo2o.health.constant.HealthMqConstants;
import com.jzo2o.rabbitmq.config.RabbitMqConfiguration;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.concurrent.TimeUnit;

/**
 * RabbitMQ延时队列
 * @author JIAN
 */
@Configuration
@Import(RabbitMqConfiguration.class)
public class DelayQueueConfiguration {
    @Bean
    public Exchange delayExchange() {
        return ExchangeBuilder
                .topicExchange(HealthMqConstants.Exchanges.HEALTH_ORDER)
                .durable(true)
                .build();
    }

    @Bean
    public Queue delayQueueIn() {
        return QueueBuilder
                .durable(HealthMqConstants.Queues.DELAY_IN)
                // 订单默认15分钟超时
                .ttl((int) TimeUnit.MINUTES.toMillis(15))
                .deadLetterExchange(HealthMqConstants.Exchanges.HEALTH_ORDER)
                .deadLetterRoutingKey(HealthMqConstants.RoutingKeys.ORDER_OVERTIME_OUT)
                .build();
    }

    @Bean
    public Queue delayQueueOut() {
        return QueueBuilder.durable(HealthMqConstants.Queues.DELAY_OUT)
                .build();
    }

    @Bean
    public Binding bindDelayQueueIn() {
        return BindingBuilder
                .bind(delayQueueIn())
                .to(delayExchange())
                .with(HealthMqConstants.RoutingKeys.ORDER_OVERTIME_IN)
                .noargs();
    }

    @Bean
    public Binding bindDelayQueueOut() {
        return BindingBuilder
                .bind(delayQueueOut())
                .to(delayExchange())
                .with(HealthMqConstants.RoutingKeys.ORDER_OVERTIME_OUT)
                .noargs();
    }
}